package com.suxin.group;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @Classname NioGroupClient
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2021/1/5 22:50
 * @Created by ASUS
 */
public class NioGroupClient {

    public static void main(String[] args) throws Exception {

        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {

                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("NioClientGroupHandler", new NioClientGroupHandler());
                        }
                    });
            System.out.println("client ready...");

            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();
            // 客户端的 channel
            Channel channel = channelFuture.channel();

            System.out.println("--------" + channel.localAddress() + "-------");

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String nextLine = scanner.nextLine();
                channel.writeAndFlush(nextLine);
            }
            channel.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            workGroup.shutdownGracefully();
        }
    }

}